﻿using Basic.FlowModel.DB;
using Basic.FlowRemoteModel;
using Basic.FlowRemoteModel.NodeMsg.Model;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Basic.FlowDAL.lmpl
{
    internal class FlowNodeMsgDAL : BasicDAL<DBFlowNodeMsg, long>, IFlowNodeMsgDAL
    {
        public FlowNodeMsgDAL ( IRepository<DBFlowNodeMsg> basicDAL ) : base(basicDAL, "node.msg")
        {
        }
        public void Add ( NodeMsgSet data )
        {
            DBFlowNodeMsg add = data.ConvertMap<NodeMsgSet, DBFlowNodeMsg>();
            add.Id = IdentityHelper.CreateId();
            this._BasicDAL.Insert(add);
        }

        public void Clear ( long flowId, long nodeId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.FlowId == flowId && a.NodeId == nodeId, a => a.Id);
            long[] clearId = this._BasicDAL.Gets(a => a.FlowId == flowId && a.ReceiveRange == FlowMsgReceiveRange.指定节点审批人 && a.ToNodeId.Contains(nodeId), a => a.Id);
            if ( clearId.IsNull() && ids.IsNull() )
            {
                return;
            }
            else if ( !clearId.IsNull() && !ids.IsNull() )
            {
                ISqlQueue<DBFlowNodeMsg> queue = this._BasicDAL.BeginQueue();
                queue.Delete(a => ids.Contains(a.Id));
                queue.UpdateOneColumn(a => a.ToNodeId == null, a => clearId.Contains(a.Id));
                _ = queue.Submit();
            }
            else if ( !ids.IsNull() )
            {
                if ( !this._BasicDAL.Delete(a => ids.Contains(a.Id)) )
                {
                    throw new ErrorException("flow.node.msg.delete.fail");
                }
            }
            else if ( !this._BasicDAL.Update(a => a.ToNodeId == null, a => clearId.Contains(a.Id)) )
            {
                throw new ErrorException("flow.node.msg.set.fail");
            }
        }
    }
}
